package fan.project1_SpeedTalkSystem.Controller;

import fan.project1_SpeedTalkSystem.Model.BlogInfo;
import fan.project1_SpeedTalkSystem.Model.JWTUtils;
import fan.project1_SpeedTalkSystem.Model.Result;
import fan.project1_SpeedTalkSystem.Service.BlogService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RequestMapping(value = "/blog")
@RestController

public class BlogController {
    @Autowired
    BlogService blogService;

    //查询博客列表

    @RequestMapping("/getList")
    public List<BlogInfo> getList() {
        List<BlogInfo> blogList = blogService.getBlogList();
        for(BlogInfo blogInfo : blogList){
            if(StringUtils.hasLength(blogInfo.getContent())){
                if(blogInfo.getContent().length()>10){
                    blogInfo.setContent(blogInfo.getContent().substring(0, 10));
                    blogInfo.setContent(blogInfo.getContent()+"...");
                }
            }

        }
        return blogList;
    }

    //根据博客id查询详细信息
    @RequestMapping("/getBlogById")
    public BlogInfo getListById(Integer id , HttpServletRequest request) {
        BlogInfo blogInfo = blogService.getBlogListById(id);
        if(blogInfo == null) {return null;}
        String userToken = request.getHeader("userToken");
        Integer userId =(Integer) JWTUtils.getMsg(userToken).getOrDefault("id",0);
        blogInfo.setAuthor( userId == blogInfo.getUserId() );
        return blogInfo ;
    }

    //新增博客
    @RequestMapping("/new")
    public Result newBlog(BlogInfo blogInfo, HttpServletRequest request) {
        log.info("新增博客 {}", blogInfo);
        if (!StringUtils.hasLength(blogInfo.getTitle())
                || !StringUtils.hasLength(blogInfo.getContent())) {
            return Result.fail("标题或内容为空", "");
        }

        try {
            String userToken = request.getHeader("userToken");
            log.info("获取到userToken {}", userToken);
            Integer userId =(Integer) JWTUtils.getMsg(userToken).get("id");
            blogInfo.setUserId(userId);
            if (blogService.insertBlog(blogInfo)) {
                return Result.success("");
            }
        } catch (Exception e) {
            return Result.fail("新建博客失败", "");
        }
        return Result.fail("新建博客失败", "");
    }

    //更新博客
    @RequestMapping("/update")
    public boolean updateBlog(BlogInfo blogInfo) {
        return blogService.updateBlogById(blogInfo);
    }

    @RequestMapping("/delete")
    public boolean deleteBlogById(Integer id) {
        return blogService.deleteBlogByid(id);
    }

}
